package com.elitesland.b2c.com.repo;

import com.elitesland.b2c.com.entity.ComAreaDO;

import java.util.List;
import java.util.Map;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;

/**
 * <p>
 * 功能说明
 * </p>
 *
 * @author fred
 * @since 2021-02-01 17:29:32
 */
@Repository
public interface ComAreaRepo extends JpaRepository<ComAreaDO ,Long>,QuerydslPredicateExecutor<ComAreaDO>{
    /**
     * 树形查询
     * @param id
     * @return
     */
    @Transactional
    @Modifying
    @Query(value = "select * from com_area WHERE id IN (select getChildLst(?1))", nativeQuery = true)
    List<ComAreaDO> getTreeByParentId(Long id);

    List<ComAreaDO> findByParentId(Long id);

    /**
     * 根据上级区域id,查询下级区域
     *
     * @param key
     * @return
     */
    @Transactional
    @Modifying
    @Query(value = "SELECT t.id as value,t.name as label,t.parent_id as parentId,case (SELECT count(*) from com_area where parent_id=t.id) WHEN 0 then 'TRUE' else 'FALSE' end as isLeaf FROM com_area t WHERE t.parent_id=?1", nativeQuery = true)
    List<Map<String, Object>> findChildrenById(Long key);
    /**
     * 根据传入的数据查询出tree
     *
     * @param ids
     * @return
     */
    @Transactional
    @Modifying
    @Query(value = "SELECT t.id as value,t.name as label,t.parent_id as parentId,case (SELECT count(*) from com_area where parent_id=t.id) WHEN 0 then 'TRUE' else 'FALSE' end as isLeaf FROM com_area t WHERE t.id in(?1)", nativeQuery = true)
    List<Map<String, Object>> findSelectedTree(List<Long> ids);

    /**
     * 根据传入的数据查询
     *
     * @param idsForSelect
     * @return
     */
    @Transactional
    @Modifying
    @Query(value = "SELECT t.id as value,t.name as label,t.parent_id as parentId,case (SELECT count(*) from com_area where parent_id=t.id) WHEN 0 then 'TRUE' else 'FALSE' end as isLeaf FROM com_area t WHERE t.parent_id in(?1)", nativeQuery = true)
    List<Map<String, Object>> findByParentIds(List<Long> idsForSelect);
}